import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_constant.dart';
import 'package:hxdj/common/utils/my_event_bus_util.dart';
import 'package:hxdj/home/home_viewmodel.dart';
import 'package:hxdj/home/order/order_model.dart';
import 'package:provider/provider.dart';

class OrderDetailViewModel extends BaseViewModel {
  String orderId = "";
  String memberId = "";

  OrderModel orderModel = OrderModel();

  OrderDetailViewModel(oId) {
    orderId = oId;
  }

  //请求数据 订单详情
  @override
  requestData({Function(dynamic)? onSuccess, Function(dynamic)? onError}) async {
    setState(ViewState.loading);
    // 去请求服务器数据.

    memberId = CommonPlugin.sharedPreferences!.getString(MyConstant.memberId) ?? "";

    Map<String, dynamic> resultMap = await DioHttpManager().request(MyApi.anmoV2OrderDetail,
        method: DioHttpManager.post, data: {"order_id": orderId, "member_id": memberId});
    // 请求成功后, 更新页面.
    if (resultMap['code'] == 0) {
      if (resultMap["data"].isNotEmpty) {
        orderModel = OrderModel.fromMap(resultMap["data"]);
      } else {
        List<dynamic> progressList = resultMap["progress"];
        Map<String, dynamic> progressMap = progressList.first;
        EasyLoading.showToast(progressMap["title"]);

        Navigator.of(context).popUntil((route) => route.isFirst);
        //返回上一个页面, 并刷新订单列表页面
        //刷新首页的订单数据
        HomeViewModel homeViewModel = Provider.of<HomeViewModel>(context, listen: false);
        homeViewModel.reloadOrderData();
        // 还有当前页面, 订单全部展示的页面,
        try {
          //刷新全部订单 ,待销费的
          MyEventBusUtil.sentEvent(MyEventBusHelp(MyEventBusTag.onMessageReceived, result: {"order_status": "1"}));
        } catch (e) {
          print("刷新订单列表失败");
        }
      }
    } else {
      EasyLoading.showToast(resultMap["msg"]);
    }

    // 更新页面.
    setState(ViewState.normal);
  }
}
